package com.plugin.manager;

import com.plugin.common.PluginService;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

/**
 * @author  laowu
 * @create  2021/8/9 16:29
 * @desc  插件管理
 **/
public class PluginManager {

    private URLClassLoader loader;

    public PluginManager(List<Plugin> plugins) throws MalformedURLException {
        init(plugins);
    }

    private void init(List<Plugin> plugins) throws MalformedURLException {
        int size = plugins.size();
        URL[] urls = new URL[size];
        for (int i = 0; i < size; i++) {
            Plugin plugin = plugins.get(i);
            String filePath = plugin.getJar();
            urls[i] = new URL("file:" + filePath);
        }
        // 将jar文件组成数组，来创建一个URLClassLoader
        loader = new URLClassLoader(urls);
    }

    public PluginService getInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 插件实例化对象，插件都是实现PluginService接口
        Class<?> clazz = loader.loadClass(className);
        return (PluginService) clazz.newInstance();
    }
}
